<!DOCTYPE html>
<html>
<head>
<#include "/common/head.html"/>
</head>
<body>
	<div class="layui-fluid">
		<div class="layui-row">
			<form method="post" class="layui-form layui-form-pane" lay-filter="form-val-filter">
				
		       	<input type="hidden" name="id">
				
				<div class="layui-form-item">
					<label class="layui-form-label">名称</label>
				    <div class="layui-input-block">
				      	<input type="text" name="name" placeholder="请输入名称"
								lay-verify="required" autocomplete="off" class="layui-input"/>
				    </div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">编码</label>
				    <div class="layui-input-block">
						<input type="text" name="code" placeholder="请输入编码"
								lay-verify="required" autocomplete="off" class="layui-input"/>
				    </div>
				</div>
				  
				  <div class="layui-form-item layui-form-text">
				    <label class="layui-form-label">权限设置</label>
				    <div class="layui-input-block">
				      <div id="rolestree"></div>
				    </div>
				  </div>
				
				<div class="layui-form-item">
				    <div class="layui-input-block">
				      <button type="submit" class="layui-btn" lay-submit lay-filter="add">提交</button>
				      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
				    </div>
				  </div>
				
			</form>
		</div>
	</div>
	<script>
	
		layui.use(function() {
			$ = layui.jquery;
			var form = layui.form, layer = layui.layer;
			var tree = layui.tree;
			xadmin.apiget('/v1/auth/tree',{},function(result){
				var auths=result.data;
				
				expandAuth(auths);
				
				tree.render({
					id:'rolestree',
				    elem: '#rolestree',
				    data: auths,
				    showCheckbox:true,
				    customName:{
				    	id: 'id',
			    	    title: 'name',
			    	    children: 'items'
				    }
				});
				
				var id=getQueryString('id');
				if(id){
					apipost('/v1/role/page',{id:id},function(result){
						var data=result.data[0];
						form.val('form-val-filter',data);
						tree.setChecked('rolestree', data.authIds);
					});
				}
			});

			form.on('submit(add)', function(data) {
				
				var auths = tree.getChecked('rolestree');
				var authIds=getSelectAuthIds(auths);
				
				var field = data.field;
				field['authIds']=authIds;
				winPost("/v1/role", convertFormParams(field));
				return false;
			});

		});
		
		function expandAuth(list){
			for(var a in list){
				list[a]['spread']=true;
				expandAuth(list[a].items);
			}
		}
		
		function getSelectAuthIds(list){
			var ids=[];
			for(var a in list){
				var items=list[a].items;
				if(items.length>0){
					var ii=getSelectAuthIds(items);
					for(var i in ii){
						ids.push(ii[i]);
					}
				}else{
					ids.push(list[a].id);
				}
			}
			return ids;
		}
		
	</script>
</body>

</html>